import { BaseEntity } from './BaseEntity';
import { ItemType, quality } from '../../shared/face/enums';

/**
 * 物品实体类
 */
export class Item extends BaseEntity {
    /** 物品名称 */
    public name: string;
    
    /** 物品描述 */
    public description: string;
    
    /** 物品类型 */
    public type: ItemType;
    
    /** 物品品质 */
    public quality: quality;
    
    /** 物品图标 */
    public icon: string;
    
    /** 物品表情符号 */
    public emoji: string;
    
    /** 物品数量 */
    public count: number;
    
    /** 最大堆叠数量 */
    public maxStack: number;
    
    /** 是否可堆叠 */
    public stackable: boolean;
    
    /** 是否可使用 */
    public usable: boolean;
    
    /** 是否可交易 */
    public tradeable: boolean;
    
    /** 是否可丢弃 */
    public droppable: boolean;
    
    /** 物品标签 */
    public tags: string[];
    
    /** 物品属性数据 */
    public data: ItemData;
    
    /** 物品价值（用于出售） */
    public value: number;
    
    /** 物品等级要求 */
    public levelRequirement: number;
    
    /** 物品使用冷却时间（毫秒） */
    public cooldown: number;
    
    /** 物品效果持续时间（毫秒） */
    public duration: number;

    constructor(id?: string) {
        super(id);
        
        this.name = '';
        this.description = '';
        this.type = ItemType.消耗品;
        this.quality = (quality as any).白色;
        this.icon = '';
        this.emoji = '';
        this.count = 1;
        this.maxStack = 999;
        this.stackable = true;
        this.usable = true;
        this.tradeable = true;
        this.droppable = true;
        this.tags = [];
        this.data = {};
        this.value = 1;
        this.levelRequirement = 1;
        this.cooldown = 0;
        this.duration = 0;
    }

    /**
     * 创建物品
     */
    public static create(config: ItemCreateConfig): Item {
        const item = new Item(config.id);
        
        item.name = config.name;
        item.description = config.description || '';
        item.type = config.type || ItemType.消耗品;
        item.quality = config.quality || (quality as any).白色;
        item.icon = config.icon || '';
        item.emoji = config.emoji || '';
        item.count = config.count || 1;
        item.maxStack = config.maxStack || 999;
        item.stackable = config.stackable !== false;
        item.usable = config.usable !== false;
        item.tradeable = config.tradeable !== false;
        item.droppable = config.droppable !== false;
        item.tags = config.tags || [];
        item.data = config.data || {};
        item.value = config.value || 1;
        item.levelRequirement = config.levelRequirement || 1;
        item.cooldown = config.cooldown || 0;
        item.duration = config.duration || 0;
        
        return item;
    }

    /**
     * 是否可以与另一个物品堆叠
     */
    public canStackWith(other: Item): boolean {
        return this.stackable &&
               other.stackable &&
               this.id === other.id &&
               this.quality === other.quality &&
               this.data === other.data;
    }

    /**
     * 堆叠物品
     */
    public stackWith(other: Item, maxAmount?: number): StackResult {
        if (!this.canStackWith(other)) {
            return {
                success: false,
                message: '物品无法堆叠',
                stackedAmount: 0,
                remainingAmount: other.count
            };
        }

        const maxStackable = maxAmount || this.maxStack;
        const canStack = Math.min(
            other.count,
            maxStackable - this.count
        );

        if (canStack <= 0) {
            return {
                success: false,
                message: '已达到最大堆叠数量',
                stackedAmount: 0,
                remainingAmount: other.count
            };
        }

        this.count += canStack;
        const remaining = other.count - canStack;

        this.updateEntity();

        return {
            success: true,
            message: `成功堆叠 ${canStack} 个物品`,
            stackedAmount: canStack,
            remainingAmount: remaining
        };
    }

    /**
     * 分割物品
     */
    public split(amount: number): Item | null {
        if (amount <= 0 || amount >= this.count) {
            return null;
        }

        if (!this.stackable) {
            return null;
        }

        const newItem = this.clone();
        newItem.count = amount;
        this.count -= amount;

        this.updateEntity();

        return newItem;
    }

    /**
     * 使用物品
     */
    public use(amount: number = 1): UseResult {
        if (!this.usable) {
            return {
                success: false,
                message: '该物品无法使用',
                effect: null
            };
        }

        if (amount <= 0 || amount > this.count) {
            return {
                success: false,
                message: '使用数量无效',
                effect: null
            };
        }

        this.count -= amount;
        this.updateEntity();

        return {
            success: true,
            message: `使用了 ${amount} 个 ${this.name}`,
            effect: this.getUseEffect(amount)
        };
    }

    /**
     * 获取使用效果
     */
    private getUseEffect(amount: number): ItemEffect | null {
        // 根据物品类型和数据返回不同的效果
        switch (this.type) {
            case ItemType.消耗品:
                return this.getConsumableEffect(amount);
            case ItemType.道具:
                return this.getToolEffect(amount);
            default:
                return null;
        }
    }

    /**
     * 获取消耗品效果
     */
    private getConsumableEffect(amount: number): ItemEffect | null {
        const effectData = this.data.effect;
        if (!effectData) return null;

        return {
            type: effectData.type || 'heal',
            value: (effectData.value || 0) * amount,
            duration: this.duration,
            target: effectData.target || 'self'
        };
    }

    /**
     * 获取道具效果
     */
    private getToolEffect(amount: number): ItemEffect | null {
        // 道具类物品的特殊效果逻辑
        return {
            type: 'tool',
            value: amount,
            duration: 0,
            target: 'self'
        };
    }

    /**
     * 获取品质名称
     */
    public getQualityName(): string {
        const qualityNames = {
            [(quality as any).白色]: '普通',
            [(quality as any).绿色]: '优秀',
            [(quality as any).蓝色]: '精良',
            [(quality as any).紫色]: '史诗',
            [(quality as any).橙色]: '传说',
            [(quality as any).红色]: '神话'
        };
        return qualityNames[this.quality] || '未知';
    }

    /**
     * 获取品质颜色
     */
    public getQualityColor(): string {
        const qualityColors = {
            [(quality as any).白色]: '#FFFFFF',
            [(quality as any).绿色]: '#00FF00',
            [(quality as any).蓝色]: '#0080FF',
            [(quality as any).紫色]: '#8000FF',
            [(quality as any).橙色]: '#FF8000',
            [(quality as any).红色]: '#FF0000'
        };
        return qualityColors[this.quality] || '#FFFFFF';
    }

    /**
     * 检查是否满足等级要求
     */
    public meetsLevelRequirement(playerLevel: number): boolean {
        return playerLevel >= this.levelRequirement;
    }

    /**
     * 验证物品数据
     */
    public validate(): any {
        const result = super.validate();

        if (!this.name || this.name.trim().length === 0) {
            result.errors.push({ field: 'name', message: '物品名称不能为空' });
        }

        if (this.count < 0) {
            result.errors.push({ field: 'count', message: '物品数量不能为负数' });
        }

        if (this.maxStack < 1) {
            result.errors.push({ field: 'maxStack', message: '最大堆叠数量必须大于0' });
        }

        if (this.value < 0) {
            result.errors.push({ field: 'value', message: '物品价值不能为负数' });
        }

        if (this.levelRequirement < 1) {
            result.errors.push({ field: 'levelRequirement', message: '等级要求必须大于0' });
        }

        result.isValid = result.errors.length === 0;
        return result;
    }
}

/**
 * 物品数据接口
 */
export interface ItemData {
    [key: string]: any;
    effect?: {
        type: string;
        value: number;
        target?: string;
    };
}

/**
 * 物品创建配置接口
 */
export interface ItemCreateConfig {
    id?: string;
    name: string;
    description?: string;
    type?: ItemType;
    quality?: quality;
    icon?: string;
    emoji?: string;
    count?: number;
    maxStack?: number;
    stackable?: boolean;
    usable?: boolean;
    tradeable?: boolean;
    droppable?: boolean;
    tags?: string[];
    data?: ItemData;
    value?: number;
    levelRequirement?: number;
    cooldown?: number;
    duration?: number;
}

/**
 * 堆叠结果接口
 */
export interface StackResult {
    success: boolean;
    message: string;
    stackedAmount: number;
    remainingAmount: number;
}

/**
 * 使用结果接口
 */
export interface UseResult {
    success: boolean;
    message: string;
    effect: ItemEffect | null;
}

/**
 * 物品效果接口
 */
export interface ItemEffect {
    type: string;          // 效果类型
    value: number;         // 效果数值
    duration: number;      // 持续时间
    target: string;        // 作用目标
}
